package com.neil.dynamic.manage.service.impl;

import com.alibaba.fastjson.JSON;
import com.neil.dynamic.manage.config.RedisConfig;
import com.neil.dynamic.manage.entity.DynamicVersion;
import com.neil.dynamic.manage.respository.DynamicVersionMapper;
import com.neil.dynamic.manage.service.inf.IDynamicVersionService;
import com.neil.dynamic.manage.service.inf.IRoutesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 *  动态版本管理
 * @ProjectName:
 * @Package:        com.neil.dynamic.manage.service.impl
 * @ClassName:      DynamicVersionServiceImpl
 * @Description:    动态版本管理
 * @Author:         Neil.Zhou
 * @CreateDate:     2019/10/14 17:51
 * @UpdateUser:     Neil.Zhou
 * @UpdateDate:     2019/10/14 17:51
 * @UpdateRemark:   The modified content
 * @Version:        1.0
 * <p>Copyright: Copyright (c) 2019/10/14</p>
 *
 */
@Slf4j
@Service
public class DynamicVersionServiceImpl implements IDynamicVersionService {

    @Autowired
    private DynamicVersionMapper mapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IRoutesService routesService;

    @Override
    public int add(DynamicVersion version) {
        version.setCreateTime(new Date());
        int result = mapper.insertSelective(version);

        //发布时，把版本信息与路由信息存入redis
        redisTemplate.opsForValue().set(RedisConfig.versionKey , String.valueOf(version.getId()));
        redisTemplate.opsForValue().set(RedisConfig.routeKey , JSON.toJSONString(routesService.getRouteDefinitions()));

        return result;
    }

    @Override
    public int update(DynamicVersion version) {
        return mapper.updateByPrimaryKeySelective(version);
    }

    @Override
    public int delete(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    /**
     * 获取最后一次发布的版本号
     * @return
     */
    @Override
    public Long getLastVersion() {
        return mapper.getLastVersion();
    }

    @Override
    public List<DynamicVersion> listAll() {
        return mapper.listAll();
    }
}
